﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace DCT.AutoUpdate.Code.Downloader
{
    public class HttpSourceLocationProtocalProvider : SourceLocationProtocalProvider
    {
        WebResponse response = null;

        public override void GetStream(SourceLocation sl, out Stream stream, out SourceInfo sourceInfo)
        {
            stream = null;
            sourceInfo = new SourceInfo();

            HttpWebRequest req = GetRequest(sl);

            WebResponse response = req.GetResponse();
            stream = response.GetResponseStream();
            sourceInfo.ContentType = response.ContentType;
            sourceInfo.Size = response.ContentLength;
        }

        public override void Dispose()
        {
            if (response != null)
            {
                response.Close();
            }
        }

        private static HttpWebRequest GetRequest(SourceLocation sl)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sl.Address);
            req.Timeout = 60000;

            if (!string.IsNullOrEmpty(sl.ReserveStrings["refer"]))
            {
                req.Referer = sl.ReserveStrings["refer"];
            }
            if (!string.IsNullOrEmpty(sl.ReserveStrings["cookies"]))
            {
                req.Headers.Add(HttpRequestHeader.Cookie, sl.ReserveStrings["cookies"]);
            }
            if(!string.IsNullOrEmpty(sl.ReserveStrings["proxyAddress"])){
                WebProxy proxy = new WebProxy();
                proxy.Address = new Uri(sl.ReserveStrings["proxyAddress"]);                
                req.Proxy = proxy;
            }

            return req;
        }
                
        
    }
}
